#include "precompile.h"

#include "sys/typedef.h"
#include "sys/error.h"
#include "sys/stringapi.h"
#include "StringHeap.h"

/*!	string structure
			4Bytes			4Bytes			4Bytes		length			4Bytes
			refcount		capacity		length		data				0
*/
SYS_API vresult _AllocMemory(uint32 bytes,vstr* pString)
{
	byte* pData = StringHeap::Instance()->Alloc(bytes);
	if(!pData)
	{
		*pString=NULL;
		return err_outofmemory;
	}
	*(reinterpret_cast<int32*>(pData)) = 0;
	*(reinterpret_cast<int32*>(pData+4)) = bytes;
	*pString=pData+12;
	return vok;
}

SYS_API vresult _ReallocMemory(uint32 newBytes,vstr s,vstr* pNewVString)
{
	if(!s)
		return _AllocMemory(newBytes,pNewVString);
	ASSERT(StringAssistant::GetStringRefCount(s)<2);
	byte* pNewData = StringHeap::Instance()->Realloc(s,newBytes);
	if(!pNewData)
	{
		*pNewVString=NULL;
		return err_outofmemory;
	}
	*(reinterpret_cast<int32*>(pNewData+4)) = newBytes;
	*pNewVString = pNewData+12;
	return vok;
}

SYS_API vresult _FreeMemory(vstr s)
{
	if(!s)
		return vok;
	ASSERT(*(reinterpret_cast<int32*>(s-12))==0);
	if(!StringHeap::Instance()->Free(s))
		return err_memoryfreefailed;
	return vok;
}


